import unittest
from suds.sudsobject import asdict
from Autotests.BaseTest import BaseManservSOAPTestCase, PartnerAndAccountAutoCreation

@PartnerAndAccountAutoCreation
class Users(BaseManservSOAPTestCase):
    def __init__(self, *args, **kwargs):
        BaseManservSOAPTestCase.__init__(self, *args, **kwargs)

    def setUp(self, *args, **kwargs):
        BaseManservSOAPTestCase.setUp(self, *args, **kwargs)
        self._baseUserInfo = {
            'partnerId': self.getPartnerForCaseInfo().id,
            'name': 'AutoTest User',
            'password': '123',
            'roleId': 1, #SuperUser
            'doubleCheckedEnabled': 0,
            'doubleCheckedUserName': None,
            'emailAddress': 'ex@mp.le'
        }

    def test_AddUser(self):
        count = self._getUserCount()
        result = self.manserv.AddUser(**self._baseUserInfo)
        self.assertTrue(result.isnumeric())
        countAfter = self._getUserCount()
        self.assertEqual(count + 1, countAfter)
        self.manserv.RemoveUser(id=result)

    def test_GetUserInfo(self):
        userId = self.manserv.AddUser(**self._baseUserInfo)
        userInfo = self.manserv.GetUserInfo(partnerId=self._baseUserInfo['partnerId'], name=self._baseUserInfo['name'],
                                            password=self._baseUserInfo['password'])
        self.assertEqual(int(userInfo.id), int(userId))
        self.assertTrue(self._compareBaseDictionaryAndResultObject(self._baseUserInfo, userInfo))
        self.manserv.RemoveUser(id=userId)

    def test_EnumerateUser(self):
        userId = self.manserv.AddUser(**self._baseUserInfo)
        result = self.manserv.EnumerateUsers(partnerId=self.getPartnerForCaseInfo().id)
        userInfo = result.userInfo[0]
        self.assertEqual(int(userInfo.id), int(userId))
        self.assertTrue(self._compareBaseDictionaryAndResultObject(self._baseUserInfo, userInfo))
        self.manserv.RemoveUser(id=userId)

    def test_ModifyUser(self):
        userId = self.manserv.AddUser(**self._baseUserInfo)
        modifiedUser = self._baseUserInfo.copy()
        modifiedUser['id'] = int(userId)
        modifiedUser['name'] = 'Modified AutoTest User'
        modifiedUser['roleId'] = 9
        result = self.manserv.ModifyUser(**modifiedUser)
        self.assertIsNone(result)
        userInfo = self._getLastUserInfo()
        self.assertTrue(self._compareBaseDictionaryAndResultObject(modifiedUser, userInfo))
        self.manserv.RemoveUser(id=userId)

    def test_RemoveUser(self):
        userId = self.manserv.AddUser(**self._baseUserInfo)
        count = self._getUserCount()
        result = self.manserv.RemoveUser(id=userId)
        self.assertIsNone(result)
        countAfter = self._getUserCount()
        self.assertEqual(count - 1, countAfter)

    def _getUserCount(self):
        result = self.manserv.EnumerateUsers(partnerId = self.getPartnerForCaseInfo().id)
        if result == '':
            return 0
        return len(result.userInfo)

    def _getLastUserInfo(self):
        result = self.manserv.EnumerateUsers(partnerId = self.getPartnerForCaseInfo().id)
        if result == '':
            return None
        return result.userInfo[0]

    def _compareBaseDictionaryAndResultObject(self, basedict, resultobj):
        import numbers
        resultdict = asdict(resultobj)
        for key, value in basedict.iteritems():
            if not isinstance(value, dict):
                if resultdict.has_key(key):
                    if value != resultdict[key]:
                        if isinstance(value, numbers.Number) and resultdict[key].isnumeric() and \
                                        int(value) == int(resultdict[key]):
                            continue
                        print('basedict[%s]=%s; resultdict[%s]=%s' %(key, value, key, resultdict[key]))
                        return False
                else:
                    #print('Key %s not found in result dictionary' %key)
                    pass
        return True

if __name__ == "__main__":
    unittest.main()